1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4 using UnityEngine.UI;
5
6 public class EnemyScript : MonoBehaviour {
7
8 public bool isVelocityEnabled = false;
9 public Vector3 velocity;
10
11 public const float maxHealth = 100f;
12 float currentHealth = maxHealth;
13 public const float impactDamage = 10f;
14
15 public GameObject explosion;
16 public GameObject reward;
17 float speed = 5f;
18
19 public Slider healthSlider;
20 private bool healthBarVisible = false;
21
22 void OnEnable () {
23 currentHealth = maxHealth;
24 UpdateHealthUI ();
25 healthSlider.gameObject.SetActive(false);
26 healthBarVisible = false;
27 }
28
29 void FixedUpdate () {
30 if (isVelocityEnabled) {
31 transform.position += velocity * Time.deltaTime;
32 }
33 }
34
35 // Update is called once per frame
36 void Update () {
37
38 }
39
40 void OnTriggerEnter2D(Collider2D collider) {
41 // Debug.Log ("EnemyScript.OnTriggerEnter2D()" + collider.gameObject);
42 if (collider.gameObject.layer == LayerMask.NameToLayer ("Bullet")) {
43 if (!healthBarVisible) {
44 healthBarVisible = true;
45 healthSlider.gameObject.SetActive(true);
46
47 }
48 float powerFactor = collider.gameObject.GetComponent<BulletScript> ().powerFactor;
49 TakeDamage (powerFactor);
50 }
51 }
52
53
54 public void TakeDamage (float powerFactor) {
55 // Debug.Log ("EnemyScript.TakeDamage(" + powerFactor + ")");
56 // Debug.Log ("currentHealth: " + currentHealth);
57 currentHealth -= impactDamage * powerFactor;
58 // Debug.Log ("after damage: " + currentHealth);
59 UpdateHealthUI();
60
61 if (currentHealth <= 0)
62 {
63 currentHealth = 0;
64 Debug.Log("Dead!");
65
66 OnDeath ();
67 }
68 }
69
70 private void UpdateHealthUI () {
71 // set slider value to current health
72 healthSlider.value = currentHealth;
73
74 // change the color of the slider
75 }
76
77 private void OnDeath () {
78 GameObject explo = Instantiate (explosion,
79 gameObject.transform.position,
80 Quaternion.identity);
81
82 // GameObject.Destroy (gameObject);
83 gameObject.SetActive(false);
84
85 GameObject.Destroy (explo,
86 explo.gameObject.GetComponent<Animator> ().GetCurrentAnimatorStateInfo(0).length);
87
88 SpawnReward ();
89 }
90
91 private void SpawnReward () {
92 GameObject rewardObj = ObjectPooler.SharedInstance.GetPooledObject(reward.tag);
93 if (rewardObj != null) {
94 rewardObj.transform.position = this.transform.position;
95 rewardObj.SetActive(true);
96 }
97
98 Vector3 velocity1 = new Vector3 (Random.Range(-1f, 1f), Random.Range(1, 2), 0);
99 velocity1.Normalize ();
100 rewardObj.GetComponent<Rigidbody2D> ().velocity = velocity1 * speed;
101 }
102 }